package com.forchange.project.core

import com.forchange.project.util.{EnvUtil, PropertiesUtil}

import java.net.{ServerSocket, Socket}

/**
 * @Author chencong
 * @Description 主程序（特质），传递逻辑、获取和关闭环境
 * @Date 1:53 下午 2021/6/27
 * @Param
 * */
trait TApplication {
  var envdata: Any = null

  //1 初始化环境
  def start(t: String)(op: => Unit) = {
    if (t == "Socket") {
      envdata = new Socket(PropertiesUtil.getValue("serverhost"), PropertiesUtil.getValue("serverport").toInt)
    } else if (t == "ServerSocket") {
      envdata = new ServerSocket(PropertiesUtil.getValue("serverport").toInt)
    } else if (t == "Spark") {
      envdata = EnvUtil.getEnv()
    }
    //2 业务逻辑
    try {
      op
    } catch {
      case exception: Exception => println("op执行失败，原因是：" + exception.getMessage)
    }
    //3 关闭环境
    if (t == "ServerSocket") {
      val serverSocket: ServerSocket = envdata.asInstanceOf[ServerSocket]
      if (!serverSocket.isClosed) {
      serverSocket.close()
      }
    }else if (t == "Socket") {
      val socket: Socket = envdata.asInstanceOf[Socket]
      if (!socket.isClosed) {
        socket.close()
      }
    }else if (t == "Spark") {
      EnvUtil.clear()
    }
  }

}
